package cn.kiliter.web.servlet;

import cn.kiliter.model.Product;
import cn.kiliter.serviece.ProductService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

@WebServlet("/changenum")
public class changenumServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String id = request.getParameter("id");
        String num = request.getParameter("num");
        ProductService service=new ProductService();
        Product p = service.findProDuctById(Integer.parseInt(id));
        Map<Product,Integer>  cart = (Map<Product, Integer>) request.getSession().getAttribute("cart");
        if(cart.containsKey(p)){
            if("0".equals(num))
                cart.remove(p);
            else {
                cart.put(p,Integer.parseInt(num));
            }
        }
        request.getSession().setAttribute("cart",cart);
        response.sendRedirect(request.getContextPath()+"/cart.jsp");


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
